# 多阶段构建 Dockerfile

# 第一阶段：构建前端
FROM node:18-alpine AS frontend-builder

# 设置工作目录
WORKDIR /app/frontend

# 复制前端项目文件（优化缓存层）
COPY frontend/package*.json ./

# 安装依赖（使用npm ci提高性能）
RUN npm ci

# 复制前端源代码
COPY frontend/ ./

# 构建前端静态文件
RUN npm run build

# 第二阶段：准备后端环境
FROM python:3.10-slim AS backend-builder

# 设置工作目录
WORKDIR /app

# 安装系统依赖（优化缓存和安全性）
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    libc6-dev \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# 复制后端依赖文件
COPY backend/requirements.txt ./

# 升级pip并安装Python依赖（优化性能）
RUN pip install --upgrade pip \
    && pip install --no-cache-dir --compile -r requirements.txt

# 最终阶段：运行环境
FROM python:3.10-slim AS production

# 设置工作目录
WORKDIR /app

# 创建非root用户
RUN useradd --create-home --shell /bin/bash app

# 配置软件源并安装运行时依赖
RUN echo "deb http://deb.debian.org/debian bookworm main" > /etc/apt/sources.list && \
    echo "deb http://deb.debian.org/debian bookworm-updates main" >> /etc/apt/sources.list && \
    echo "deb http://security.debian.org/debian-security bookworm-security main" >> /etc/apt/sources.list && \
    apt-get clean && \
    apt-get update --fix-missing && \
    apt-get install -y --no-install-recommends \
        curl \
        ca-certificates \
        gnupg \
        lsb-release && \
    curl -fsSL https://deb.nodesource.com/setup_18.x | bash - && \
    apt-get install -y --no-install-recommends nodejs && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# 从构建阶段复制Python依赖
COPY --from=backend-builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
COPY --from=backend-builder /usr/local/bin /usr/local/bin

# 复制后端代码
COPY backend/ ./backend/

# 复制示例题目文件
COPY sample_questions.json ./

# 从前端构建阶段复制静态文件
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist/

# 复制前端源码（用于开发模式）
COPY frontend/ ./frontend/

# 创建数据库目录
RUN mkdir -p /app/data

# 设置环境变量
ENV PYTHONPATH=/app:/app/backend
ENV PYTHONUNBUFFERED=1
ENV DATABASE_URL=sqlite:///./data/questions.db

# 创建启动脚本（确保总是存在）
RUN echo '#!/bin/bash' > /app/start.sh && \
    echo 'set -e' >> /app/start.sh && \
    echo '' >> /app/start.sh && \
    echo '# 日志函数' >> /app/start.sh && \
    echo 'log() {' >> /app/start.sh && \
    echo '    echo "[$(date '\''+%Y-%m-%d %H:%M:%S'\'')] $1"' >> /app/start.sh && \
    echo '}' >> /app/start.sh && \
    echo '' >> /app/start.sh && \
    echo '# 错误处理函数' >> /app/start.sh && \
    echo 'handle_error() {' >> /app/start.sh && \
    echo '    log "ERROR: $1"' >> /app/start.sh && \
    echo '    exit 1' >> /app/start.sh && \
    echo '}' >> /app/start.sh && \
    echo '' >> /app/start.sh && \
    echo '# 检查数据库目录' >> /app/start.sh && \
    echo 'if [ ! -d "/app/data" ]; then' >> /app/start.sh && \
    echo '    log "Creating data directory..."' >> /app/start.sh && \
    echo '    mkdir -p /app/data' >> /app/start.sh && \
    echo 'fi' >> /app/start.sh && \
    echo '' >> /app/start.sh && \
    echo '# 检查是否需要启动开发模式' >> /app/start.sh && \
    echo 'if [ "$DEV_MODE" = "true" ]; then' >> /app/start.sh && \
    echo '    log "Starting in development mode..."' >> /app/start.sh && \
    echo '    if command -v node >/dev/null 2>&1; then' >> /app/start.sh && \
    echo '        log "Starting frontend development server..."' >> /app/start.sh && \
    echo '        cd /app/frontend || handle_error "Failed to change to frontend directory"' >> /app/start.sh && \
    echo '        npm run dev &' >> /app/start.sh && \
    echo '        FRONTEND_PID=$!' >> /app/start.sh && \
    echo '        cd /app || handle_error "Failed to change back to app directory"' >> /app/start.sh && \
    echo '        log "Starting backend server..."' >> /app/start.sh && \
    echo '        python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload &' >> /app/start.sh && \
    echo '        BACKEND_PID=$!' >> /app/start.sh && \
    echo '        wait $FRONTEND_PID $BACKEND_PID' >> /app/start.sh && \
    echo '    else' >> /app/start.sh && \
    echo '        log "Node.js not found, starting backend only..."' >> /app/start.sh && \
    echo '        python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload' >> /app/start.sh && \
    echo '    fi' >> /app/start.sh && \
    echo 'else' >> /app/start.sh && \
    echo '    log "Starting in production mode..."' >> /app/start.sh && \
    echo '    if [ ! -d "/app/backend" ]; then' >> /app/start.sh && \
    echo '        handle_error "Backend directory not found"' >> /app/start.sh && \
    echo '    fi' >> /app/start.sh && \
    echo '    log "Starting production server..."' >> /app/start.sh && \
    echo '    python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --workers 1' >> /app/start.sh && \
    echo 'fi' >> /app/start.sh

# 设置执行权限
RUN chmod +x /app/start.sh

# 更改文件所有权
RUN chown -R app:app /app

# 切换到非root用户
USER app

# 暴露端口
EXPOSE 8000

# 健康检查（改进检查逻辑）
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:8000/health || curl -f http://localhost:8000/ || exit 1

# 启动命令
CMD ["/app/start.sh"]